<template>
  <div class="history-detail-container">
    <div class="history-detail-header">
      <h1>{{ t('history_detail') }}</h1>
      <el-button @click="goBack" plain>{{ t('back') }}</el-button>
    </div>
    
    <div class="history-detail-content">
      <div class="detail-card">
        <div class="detail-header">
          <div class="detail-title">
            <span class="detail-number">编号：@{{ detail.num_sn }}</span>
            <h2 style="color: #333333; font-weight: 500;" >{{ t(questionTitle) }}</h2>
          </div>
        </div>
        
        <div class="detail-logos">
          <div class="logo-container">
            <img :src="'https://aiw.oss-cn-beijing.aliyuncs.com/logo.png'" alt="Logo" class="logo-img" />
          </div>
          <div class="logo-container">
            <img :src="'https://aiw.oss-cn-beijing.aliyuncs.com/huawei1.png'" alt="Huawei" class="logo-img" />
          </div>
          <div class="logo-container kc-logo">
            <img :src="kc" alt="KC" class="logo-img" />
          </div>
        </div>
        
        <!-- AI输出内容区域 -->
        <div class="ai-output" v-html="aiResponse">
        </div>
        
        <!-- 解决方案区域 -->
        <div class="solution-section">
          <div class="section-title">— {{t('can_solve_problem')}} —</div>
          
          <div  class="solution-content">
            <div class="solution-header" @click="toggleSolution">
              <span>{{ t('history_detail_text1') }}</span>
              <el-icon :class="{ 'is-active': showSolution }">
                <ArrowDown v-if="!showSolution" />
                <ArrowUp v-else />
              </el-icon>
            </div>
            
            <div v-show="showSolution" class="solution-text" v-html="detail.solution"></div>
          </div>
          
          <!-- <div v-else class="solution-locked">
            <el-button type="primary" @click="viewSolution">查看解决方案</el-button>
          </div> -->
        </div>
        
        <!-- 二维码区域 -->
        <div class="qrcode-section" v-if="detail.qrcode">
          <img :src="detail.qrcode" alt="QR Code" class="qrcode-img" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';
import kc from '@/assets/images/kc.png';
import { useLanguageStore } from '@/store/languageStore';
import { useTranslateData } from '@/hooks/useTranslateData';
const route = useRoute();
const router = useRouter();
const { t } = useLanguageStore();
const { translateObjectProperties } = useTranslateData();

// 详情数据
const detail = ref({});
const questionTitle = ref('');
const aiResponse = ref('');
const showSolution = ref(false);

// 定时器管理
const typingTimer = ref(null);

// 获取历史详情
const fetchHistoryDetail = async () => {
  const { history_id } = route.query;
  
  if (!history_id) {
    ElMessage.error('参数错误');
    router.push('/user-center');
    return;
  }
  
  try {
    const res = await request({
      url: '/v6/index/getPredict',
      method: 'post',
      data: {
        history_id,
        flag: 0,
        isHidden: 2
      }
    });
    
    if (res.code === 0 && res.data) {
      // 使用 hook 翻译响应数据
      detail.value = translateObjectProperties(res.data);
      questionTitle.value = res.data.question_msg || '';
      
      // 处理体质查询和症状查询的特殊结果
      if (res.data.result_type === 99 || res.data.result_type === 98) {
        handleSpecialQueryResult(res.data);
      } else {
        // 组装AI响应数据并模拟打字机效果
        combineAiData();
      }
    } else {
      ElMessage.error(res.msg || '获取历史详情失败');
    }
  } catch (error) {
    console.error('获取历史详情失败:', error);
    ElMessage.error('error');
  }
};

// 处理体质查询和症状查询的特殊结果
const handleSpecialQueryResult = (data) => {
  questionTitle.value = t(data.question_msg) || '';
  let responseText = '';
  
  if (data.result_type === 99) {
    // 体质查询
    responseText = `${t('query_sucdess_title')}`;
    
    const result = data.result;
    
    // 先拼接五运六气信息
    if (result.wuyun_liuqi && result.wuyun_liuqi.success) {
      const wuyun = result.wuyun_liuqi;
      
      // 添加调试日志
      console.log('五运六气数据:', wuyun);
      console.log('all_special_years:', wuyun.all_special_years);
      console.log('all_periods:', wuyun.all_periods);
      
      let wuyunText = '\n\n【五运六气信息】\n';
      
      if (wuyun.ganzhi_cn && wuyun.year_type) {
        wuyunText += `干支年份：${wuyun.ganzhi_cn}（${wuyun.year_type}）\n`;
      }
      if (wuyun.jichu_qihou) {
        wuyunText += `基础气候：${wuyun.jichu_qihou}\n`;
      }
      if (wuyun.yinshi_tiaoli) {
        wuyunText += `饮食调理：${wuyun.yinshi_tiaoli}\n`;
      }
      
      // 拼接当前年份是否为特殊年份
      if (wuyun.special_info && wuyun.special_info.is_special) {
        wuyunText += `\n【当前年份】\n`;
        wuyunText += `${wuyun.special_info.ganzhi}年 - ${wuyun.special_info.description}\n`;
      }
      
      // 拼接该地支类型下所有特殊年份
      if (wuyun.all_special_years && Array.isArray(wuyun.all_special_years) && wuyun.all_special_years.length > 0) {
        wuyunText += `\n【该属相所有特殊年份】\n`;
        wuyun.all_special_years.forEach(item => {
          wuyunText += `${item.full_text}\n`;
        });
      } else {
        console.warn('all_special_years 数据缺失（可能是旧的历史记录），请重新查询');
      }
      
      // 拼接该属相的所有时段信息
      if (wuyun.all_periods && Array.isArray(wuyun.all_periods) && wuyun.all_periods.length > 0) {
        wuyunText += `\n【分时段(阳历)健康影响与调理】\n`;
        wuyun.all_periods.forEach((period) => {
          // 格式化日期显示
          const startDate = period.start.replace('-', '月') + '日';
          const endDate = period.end.replace('-', '月') + '日';
          
          wuyunText += `${startDate}-${endDate}左右 | `;
          
          // 主气和客气
          if (period.zhuqi && period.keqi) {
            wuyunText += `主气${period.zhuqi}+客气${period.keqi}`;
          }
          
          // 气候特点
          if (period.qihou) {
            wuyunText += `(${period.qihou})`;
          }
          
          wuyunText += `\n`;
          
          // 健康影响
          if (period.desc) {
            wuyunText += `健康影响：${period.desc}\n`;
          }
          
          wuyunText += `\n`;
        });
      } else {
        console.warn('all_periods 数据缺失（可能是旧的历史记录），请重新查询');
        // 兼容旧数据：如果有 current_period，显示提示信息
        if (wuyun.current_period) {
          wuyunText += `\n【提示】此为旧版历史记录，请重新进行体质查询以获取完整的五运六气信息\n`;
        }
      }
      
      if (wuyun.tongyong_guilu) {
        wuyunText += `${wuyun.tongyong_guilu}`;
      }
      
      responseText += wuyunText;
    }
    
    // 添加基本信息
    const fields = [];
    if (result.year_end) fields.push(`- ${result.year_end}`);
    if (result.zodiac) fields.push(`- ${result.zodiac}`);
    if (result.month_day) fields.push(`- ${result.month_day}`);
    if (result.animal_ill) fields.push(`- ${result.animal_ill}`);
    if (result.birth_place_description) fields.push(`- ${result.birth_place_description}`);
    if (result.detail_time) fields.push(`- ${result.detail_time}`);
    
    if (fields.length > 0) {
      responseText += '\n\n' + fields.join('\n');
    }
    
    // 处理预测结果
    if (result.predict_res && result.predict_res.predictRes) {
      responseText += '\n\n【未来预测】\n';
      result.predict_res.predictRes.forEach(item => {
        if (item.predict_year) {
          responseText += `\n${item.predict_year}${t('year')}\n`;
        }
        const yearDetails = [item.five_yun, item.six_qi, item.six_tizhi, item.tizhi_and_tiangan]
          .filter(Boolean)
          .join(' ');
        if (yearDetails) {
          responseText += `${yearDetails}\n`;
        }
        if (item.month && typeof item.month === 'object') {
          Object.entries(item.month).forEach(([key, value]) => {
            if (value) {
              responseText += `--${key}${t('month')}： ${value}\n`;
            }
          });
        }
      });
    }
  } else if (data.result_type === 98) {
    // 症状查询
    responseText = `${t('query_sucdess_title')}\n\n`;

    const formulas = Array.isArray(data.result)
      ? data.result
      : (data.result && typeof data.result === 'object')
          ? Object.values(data.result)
          : [];

    if (formulas.length > 0) {
      formulas.forEach((formula, index) => {
        responseText += `${index + 1}. ${formula.name_zh_cn || ''}\n`;
        if (formula.ingredients_zh_cn) {
          responseText += `   成分：${formula.ingredients_zh_cn}\n`;
        }
        responseText += '\n';
      });
    } else {
      responseText += `${t('no_pharmacy')}\n`;
    }
  }
  
  // 模拟打字机效果
  simulateTyping(responseText);
};

// 组装AI响应数据 - 修改为确保所有模块都显示内容
const combineAiData = () => {
  let aiRes = `══════════════════════\n`;
  aiRes += `★ ${t('history_detail_text2')} ★\n`;
  aiRes += `══════════════════════\n\n`;

  const data = detail.value;

  // 基础信息 - 移除过多限制条件，让更多模块可以显示
  // if (data.is_get_profit && !(data.is_special_medical == 1 && [59, 58, 75].includes(data.question_id))) {
  //   aiRes += `📌 ${data.result_title?.title_1 || ''} \n`;
  //   aiRes += `   → ${t(data.is_get_profit)} \n\n`;
  // }
  // if (data.me_wants && !(data.is_special_medical == 1 && [59, 58, 75].includes(data.question_id))) {
  //   aiRes += `📌 ${data.result_title?.title_2 || ''} \n`;
  //   aiRes += `   → ${t(data.me_wants)} \n\n`;
  // }
  // if (data.ta_idea && !(data.is_special_medical == 1 && [59, 58, 75].includes(data.question_id))) {
  //   aiRes += `📌 ${data.result_title?.title_3 || ''} \n`;
  //   aiRes += `   → ${t(data.ta_idea)} \n\n`;
  // }

  // 日期区间 - 所有模块都尝试显示
  if (data.startenddate && data.startenddate.length > 0 && data.startenddate !== t('wu')) {
    aiRes += `📅 ${t(data.startenddate)} \n\n`;
  }

  // 健康状态 - 移除部分限制条件，更多模块可以显示
  if (data.health_status && (data.contact != 2 || data.is_special_medical == 1 ||
      [58, 59, 75].includes(data.question_id))) {
    aiRes += `❤️ ${t(data.health_status)} \n\n`;
  }

  // 年月日信息 - 所有模块都显示
  const isAssignDate = data.date1 && data.date1.length > 0;

  // if (data.year_good) {
  //   aiRes += `📅 ${t('history_detail_year')}  ${t(data.year_good || '')} `;
  //   if (data.is_special) {
  //     aiRes += data.hui ? '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
  //   } else {
  //     aiRes += `${data.date_diff || ''}`;
  //   }
  //   aiRes += `\n`;
  // }

  // if (data.month_good) {
  //   aiRes += `📅 ${t('history_detail_month')} ${data.month_good || ''} `;
  //   if (data.is_special) {
  //     aiRes += data.hui ? '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
  //   } else {
  //     aiRes += `${data.date_diff || ''} `;
  //   }
  //   aiRes += `\n`;
  // }

  // if (data.day_good) {
  //   aiRes += `📅 ${t('history_detail_day')} ${data.day_good || ''} `;
  //   if (data.is_special) {
  //     aiRes += data.hui ? '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
  //   } else {
  //     aiRes += `${data.date_diff || ''} `;
  //   }
  //   aiRes += `\n`;
  // }

  // 不可控事件 - 所有模块都显示
  if (data.is_coflict !== undefined || data.is_special !== undefined) {
    aiRes += `📅 ${t('history_detail_text3')}`;
    aiRes += (data.is_coflict==1 && data.is_special==1) ? '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
    aiRes += `\n`;
  }

  // 指定日期相关 - 所有模块都显示
  if (isAssignDate && data.date1) {
    if (data.deal_152232 == 0) {
      if (data.is_month_coflict != 1 && data.is_date_coflict != 1) {
        aiRes += `📅 ${data.date1} `;
      }
      aiRes += (data.is_month_coflict == 1 || data.is_date_coflict == 1) ?
               '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
      aiRes += `\n`;
    }

    // 第二层不可控事件 - 所有模块都显示
    if (data.is_second_coflict !== undefined) {
      aiRes += `⚠️ ${t('history_detail_text4')} `;
      aiRes += (data.is_second_coflict == 1 && data.is_special == 1) ?
               '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
      aiRes += `\n`;
    }



    // 预期结果 - 所有模块都显示
    if (data.is_coflict !== undefined) {
      aiRes += `🚨 ${t('history_detail_text5')} `;
      aiRes += (data.is_coflict==1 && data.is_special==1) ?
               '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
      aiRes += `\n`;
    }
  }


  if (!data.date1 && data.is_second_coflict !== undefined) {
    aiRes += `📅 ${t('uncontrollable_events_this_year')} `;
    aiRes += (data.is_second_coflict == 1 && data.is_special == 1) ?
        '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
    aiRes += `\n`;
  }

  // 股市特殊处理 - 保持原逻辑
  if (data.contact_text == t('stock') && data.startenddate && data.startenddate.length > 0) {
    if (data.startenddate != t('wu')) {
      aiRes += `📈 ${data.startenddate} `;
      if (data.is_special) {
        aiRes += data.easy!=0 ? '✅ '+ t('easy_to_achieve') : '❌ '+ t('difficult_to_achieve');
      } else {
        aiRes += `${data.date_diff || ''}`;
      }
      aiRes += `\n`;
    }
  }

  // 有无利益 - 所有模块都显示
  if (data.last_num_text) {
    aiRes += `💰 ${t('profit')}: ${data.last_num_text} \n\n`;
  }

  // 中医板块 - 保持原逻辑
  if (data.is_special_medical == 1) {
    aiRes += `🌿 ${t('improve_time')}: \n`;
    if (data.ta_idea_list && data.ta_idea_list.length > 0) {
      for (let i = 0; i < data.ta_idea_list.length; i++) {
        aiRes += `   → ${data.ta_idea_list[i]} \n`;
      }
    }
    aiRes += `\n`;

    if (data.health_status) {
      aiRes += `❤️ ${t(data.health_status)} \n\n`;
    }
  }

  // 心态与情绪 - 所有模块都显示（移除 is_special_medical != 1 限制）
  // if (data.me_xintai || data.things_degree || data.me_xinli) {
  //   if (data.me_xintai) {
  //     aiRes += `📌 ${data.result_title?.title_8 || t('mind_and_mood')} \n`;
  //     aiRes += `   → ${t(data.me_xintai)} \n\n`;
  //   }

  //   if (data.things_degree) {
  //     aiRes += `📌 ${data.result_title?.title_9 || t('difficulty_of_thing')} \n`;
  //     aiRes += `   → ${t(data.things_degree)} \n\n`;
  //   }

  //   if (data.me_xinli) {
  //     aiRes += `📌 ${data.result_title?.title_10 || t('mental_advice')} \n`;
  //     aiRes += `   → ${t(data.me_xinli)} \n\n`;
  //   }
  // }

  // 解决方案显示判断
  if (data.solution) {
    // solution在单独区域显示，这里不重复
  }

  // 不再使用兜底机制自动显示所有字段，避免显示注释掉的内容
  // 如果需要显示更多内容，应该在上面明确添加对应的判断逻辑

  // 模拟打字机效果（不预处理高亮，在显示时处理）
  simulateTyping(aiRes);
};

// 高亮包含特定关键词的行
const highlightSpecificKeywords = (text) => {
  const highlightKeywords = ['uncontrollable_events', 'uncontrollable_events_this_year', 'history_detail_text4', 'history_detail_text5', 'history_detail_text3'];
  const lines = text.split('\n');
  
  return lines.map(line => {
    const shouldHighlight = highlightKeywords.some(keyword => 
      line.includes(keyword) || line.includes(t(keyword))
    );
    
    if (shouldHighlight && line.trim()) {
      return `<span style="background-color: #ffeb3b; padding: 2px 4px; border-radius: 4px; font-weight: bold;">${line}</span>`;
    }
    return line;
  }).join('\n');
};

// 清除所有定时器
const clearAllTimers = () => {
  if (typingTimer.value) {
    clearInterval(typingTimer.value);
    typingTimer.value = null;
  }
};

// 打字机效果
const simulateTyping = (text) => {
  // 先清除之前的定时器
  clearAllTimers();
  
  let index = 0;
  aiResponse.value = '';
  
  typingTimer.value = setInterval(() => {
    if (index < text.length) {
      const currentText = text.substring(0, index + 1);
      // 在每次更新时应用高亮效果
      aiResponse.value = highlightSpecificKeywords(currentText);
      index++;
    } else {
      clearAllTimers();
    }
  }, 50); // 每50毫秒显示一个字
};

// 查看解决方案
const viewSolution = () => {
  ElMessage.info(t('history_detail_text6'));
};

// 切换解决方案显示/隐藏
const toggleSolution = () => {
  showSolution.value = !showSolution.value;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 页面加载时获取历史详情
onMounted(() => {
  fetchHistoryDetail();
});

// 监听路由query变化，重新获取数据
watch(() => route.query, (newQuery, oldQuery) => {
  // 当query参数发生变化时，重新获取历史详情
  if (newQuery.history_id !== oldQuery?.history_id) {
    // 先清除所有定时器，防止画面抖动
    clearAllTimers();
    
    // 重置数据状态
    detail.value = {};
    questionTitle.value = '';
    aiResponse.value = '';
    showSolution.value = false;
    
    // 重新获取数据
    fetchHistoryDetail();
  }
}, { immediate: false, deep: true });

// 组件卸载时清理定时器
onUnmounted(() => {
  clearAllTimers();
});
</script>

<style scoped>
.history-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 20px;
}

.history-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.history-detail-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.detail-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-title {
  margin-bottom: 20px;
}

.detail-number {
  color: #409eff;
  font-size: 14px;
  display: block;
  margin-bottom: 10px;
}

.detail-title h2 {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.detail-logos {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  width: 100%;
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  flex: 1;
  margin: 0 10px;
  border-radius: 6px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 8px;
}

.logo-container:first-child {
  margin-left: 0;
}

.logo-container:last-child {
  margin-right: 0;
}

.kc-logo {
  background-color: #f0f0f0;
}

.logo-img {
  max-height: 40px;
  max-width: 100%;
  object-fit: contain;
}

.ai-output {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  min-height: 200px;
  white-space: pre-wrap;
  line-height: 1.6;
  font-size: 15px;
  color: #333333;
  font-weight: 500;
  overflow: hidden;
}

.solution-section {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.section-title {
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #333;
}

.solution-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
}

.solution-text {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 0 0 4px 4px;
  margin-top: 1px;
}

.solution-locked {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.qrcode-section {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.qrcode-img {
  width: 160px;
  height: 160px;
}

.is-active {
  transform: rotate(180deg);
}
</style>
